package com.doctor.comm;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;

public class ImageHelper {

	
	/**
	 * 把图片转换成圆形来显示
	 * @param bitmap
	 * @return
	 */
	public static Bitmap getRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left,top,right,bottom,dst_left,dst_top,dst_right,dst_bottom;
        if (width <= height) {
                roundPx = width / 2;
                top = 0;
                bottom = width;
                left = 0;
                right = width;
                height = width;
                dst_left = 0;
                dst_top = 0;
                dst_right = width;
                dst_bottom = width;
        } else {
                roundPx = height / 2;
                float clip = (width - height) / 2;
                left = clip;
                right = width - clip;
                top = 0;
                bottom = height;
                width = height;
                dst_left = 0;
                dst_top = 0;
                dst_right = height;
                dst_bottom = height;
        }
         
        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
         
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int)left, (int)top, (int)right, (int)bottom);
        final Rect dst = new Rect((int)dst_left, (int)dst_top, (int)dst_right, (int)dst_bottom);
        final RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);
         
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
}
	
	public interface TakePictureCallback{
		public void onGetImageName(Uri imageUri);
	}
	/**
	 * 相册或拍照选取图片
	 * @param activity
	 * @param requestCode
	 */
	public static void selectPicture(Fragment fragment,int requestCode,TakePictureCallback callback){
		int REQUEST_CODE;
		switch (requestCode) {
		
		case ConstConfig.CHOOSE_PICTURE:
			Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);			
			REQUEST_CODE = ConstConfig.CHOOSE_PICTURE;			
			openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
			fragment.startActivityForResult(openAlbumIntent,REQUEST_CODE);
			break;
		
		case ConstConfig.TAKE_PICTURE:
			Uri imageUri = null;
			String imageName = null;
			Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);			
			REQUEST_CODE = ConstConfig.TAKE_PICTURE;
			imageName = (System.currentTimeMillis()/1000)+".jpg";
			//指定存放照片的文件夹，文件夹不存在则创建
			File file=new File(ConstConfig.Camera_FILE);
			if (!file.exists()) {
				file.mkdirs();
			}
			imageUri = Uri.fromFile(new File(file,imageName));
			openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
			callback.onGetImageName(imageUri);
			fragment.startActivityForResult(openCameraIntent,REQUEST_CODE);
			break;
			
		default:
			break;
	}
	}
	
	/**
	 * 相册或拍照选取图片
	 * @param activity
	 * @param requestCode
	 */
	public static void selectPicture(Activity activity,int requestCode,TakePictureCallback callback){
		int REQUEST_CODE;
		switch (requestCode) {
		
		case ConstConfig.CHOOSE_PICTURE:
			REQUEST_CODE = ConstConfig.CHOOSE_PICTURE;
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
				//小于4.4的版本
				Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
				openAlbumIntent.addCategory(Intent.CATEGORY_OPENABLE);
				openAlbumIntent.setType("image/*");			
				activity.startActivityForResult(openAlbumIntent,REQUEST_CODE);
			} else {
				//大于等于4.4的版本
				Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
	            intent.addCategory(Intent.CATEGORY_OPENABLE);
	            intent.setType("image/*");
	            activity.startActivityForResult(intent, REQUEST_CODE);
			}
			break;
		
		case ConstConfig.TAKE_PICTURE:
			Uri imageUri = null;
			String imageName = null;
			Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);			
			REQUEST_CODE = ConstConfig.TAKE_PICTURE;
			imageName = (System.currentTimeMillis()/1000)+".jpg";
			//指定存放照片的文件夹，文件夹不存在则创建
			File file=new File(ConstConfig.Camera_FILE);
			if (!file.exists()) {
				file.mkdirs();
			}
			imageUri = Uri.fromFile(new File(file,imageName));
			openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
			callback.onGetImageName(imageUri);
			activity.startActivityForResult(openCameraIntent,REQUEST_CODE);
			break;
			
		default:
			break;
	}
	}
	
	
	/**
	 * 获取图片bitmap
	 * @param in
	 * @return
	 */
	public static Bitmap getBitmapFromPath(Activity activity,String path){
		if (path!=null) {
			//避免bitmap outofmemory exception
//			int maxNumOfPixels = 1024*1024;  //最大返回1M大小的图片
			
//		    BitmapFactory.Options opts = new BitmapFactory.Options();  
//		    opts.inJustDecodeBounds = true;
//		    BitmapFactory.decodeStream(in, null,opts);  
//		    opts.inSampleSize = computeSampleSize(opts, -1, maxNumOfPixels); 
//		    opts.inJustDecodeBounds = false;  
		    try {
		    	BitmapFactory.Options options=new BitmapFactory.Options();
				options.inDither=false;  //不进行图片抖动处理                   
				options.inPurgeable=true; //用于存储Pixel的内存空间在系统内存不足时可以被回收                
				options.inInputShareable=true; //以上options的两个属性必须联合使用才会有效果            
//				options.inTempStorage=new byte[500 * 1024];//自行在Android上开辟一段内存空间，存储的图片放在该内存中
				FileInputStream in = new FileInputStream(new File(path));
			    	if(in != null) {
//					Bitmap bitmap = BitmapFactory.decodeStream(in, null,opts);
//			    		Bitmap bitmap = BitmapFactory.decodeStream(in);
			    		//调用本地方法decodeFileDescriptor节省内存
			    		Bitmap bitmap = BitmapFactory.decodeFileDescriptor(in.getFD(), null, options);
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					return bitmap;
		    	}
		    } catch (OutOfMemoryError err) {
		    	err.printStackTrace();
		    } catch (FileNotFoundException err) {
				// TODO: handle exception
		    	err.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		return null;
	}	
	
	
	/**
	 * 返回按比例宽高的图片
	 * @param context
	 * @param uri
	 * @param width
	 * @param height
	 * @return
	 */
	public static Bitmap getBitmapByUri(Context context, Uri uri, int width, int height){
		String path=FileHelper.uri2Path(context, uri);
		if (path==null) {
			return null;
		}
		BitmapFactory.Options options=new BitmapFactory.Options();
		//设置为true不读取图片
		options.inJustDecodeBounds=true;
		//只需获取其宽高信息，此时bitmap是null的
		Bitmap bitmap=BitmapFactory.decodeFile(path,options);
		//重新设置为false就可读取图片
		options.inJustDecodeBounds=false;
		//获取图片宽高
		int oldWidth=options.outWidth;
		int oldHeight=options.outHeight;
		//计算图片宽高比例
		int ratio=1;
		if (oldWidth>=oldHeight && oldWidth>width) {
			//如果宽度大的话根据宽度固定大小个来缩放 
			ratio=oldWidth/width;
		} else if(oldWidth<oldHeight && oldHeight>height) {
			//如果高度高的话根据宽度固定大小来缩放
			ratio=oldHeight/height;
		}
		
		if (ratio<=0) {
			ratio=1;
		}
		//设置图片的缩放比例
		options.inSampleSize=ratio;
		//读取图片
		bitmap=BitmapFactory.decodeFile(path,options);
		return bitmap;
	}
	
	
	
	
    /**
     * 获取图片类型
     * @param file
     * @return
     */
    public static String getImageType(File file){
        if(file == null||!file.exists()){
            return null;
        }
        InputStream in = null;
        try {
            in = new FileInputStream(file);
            String type = getImageType(in);
            return type;
        } catch (IOException e) {
            return null;
        }finally{
            try{
                if(in != null){
                    in.close();
                }
            }catch(IOException e){
            }
        }
    }
    
    /**
     * detect bytes's image type by inputstream
     * @param in
     * @return
     * @see #getImageType(byte[])
     */
    public static String getImageType(InputStream in) {
        if(in == null){
            return null;
        }
        try{
            byte[] bytes = new byte[8];
            in.read(bytes);
            return getImageType(bytes);
        }catch(IOException e){
            return null;
        }
    }

    /**
     * detect bytes's image type
     * @param bytes 2~8 byte at beginning of the image file  
     * @return image mimetype or null if the file is not image
     */
    public static String getImageType(byte[] bytes) {
        if (isJPEG(bytes)) {
            return "jpg";
        }
        if (isGIF(bytes)) {
            return "gif";
        }
        if (isPNG(bytes)) {
            return "png";
        }
        if (isBMP(bytes)) {
            return "bmp";
        }
        return null;
    }

    private static boolean isJPEG(byte[] b) {
        if (b.length < 2) {
            return false;
        }
        return (b[0] == (byte)0xFF) && (b[1] == (byte)0xD8);
    }

    private static boolean isGIF(byte[] b) {
        if (b.length < 6) {
            return false;
        }
        return b[0] == 'G' && b[1] == 'I' && b[2] == 'F' && b[3] == '8'
                && (b[4] == '7' || b[4] == '9') && b[5] == 'a';
    }

    private static boolean isPNG(byte[] b) {
        if (b.length < 8) {
            return false;
        }
        return (b[0] == (byte) 137 && b[1] == (byte) 80 && b[2] == (byte) 78
                && b[3] == (byte) 71 && b[4] == (byte) 13 && b[5] == (byte) 10
                && b[6] == (byte) 26 && b[7] == (byte) 10);
    }

    private static boolean isBMP(byte[] b) {
        if (b.length < 2) {
            return false;
        }
        return (b[0] == 0x42) && (b[1] == 0x4d);
    }
	
    
	 /**
	  * 图片缩略图
	  * @param path 图片路径
	  * @param width 缩略图宽度
	  * @param height 缩略图高度
	  * @return
	  */
	 public static Drawable getThumbPic(String path, int width, int height){
		 if (path==null || "".equals(path)) {
			return null;
		}
		 File pic=new File(path);
		 if (!pic.exists() || !pic.isFile()) {
			return null;
		}
		 
		 BitmapFactory.Options options=new BitmapFactory.Options();
		 options.inDither=false;                     
		 options.inPurgeable=true;                 
		 options.inInputShareable=true;             
		 options.inTempStorage=new byte[100*1024];
		 //设置为true只读取图片信息，不会读取图片数据
		 options.inJustDecodeBounds=true;
		 //此时返回的bitmap为空
		 BitmapFactory.decodeFile(path, options);
		 //图片原始宽度
		 int w=options.outWidth;
		 //图片原始高度
		 int h=options.outHeight;
		 int widthRatio=w/width;
		 int heightRatio=h/height;
		 //压缩比例
		 int compressRatio=1;
		 
		 if (widthRatio>1 || heightRatio>1) {
			 //压缩比例取宽高比例较大者
			compressRatio=Math.max(widthRatio, heightRatio);
		}
		 
		 options.inSampleSize=compressRatio;
		 FileInputStream imgStream = null;
		 Drawable mDrawable = null;
		 try {
			imgStream=new FileInputStream(pic);
			options.inJustDecodeBounds=false;
//			mDrawable=new BitmapDrawable(BitmapFactory.decodeStream(imgStream, null, options));
			//调用本地方法decodeFileDescriptor节省内存
			mDrawable=new BitmapDrawable(BitmapFactory.decodeFileDescriptor(imgStream.getFD(), null, options));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				if (imgStream!=null) {
					imgStream.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		 return mDrawable;
	 }	 
	 

	 /**
	  * 图片缩略图
	  * @param path 图片路径
	  * @param width 缩略图宽度
	  * @param height 缩略图高度
	  * @return
	  */
	 public static Bitmap getThumbBitmap(String path, int width, int height){
		 if (path==null || "".equals(path)) {
			return null;
		}
		 File pic=new File(path);
		 if (!pic.exists() || !pic.isFile()) {
			return null;
		}
		 
		 BitmapFactory.Options options=new BitmapFactory.Options();
		 options.inDither=false;                     
		 options.inPurgeable=true;                 
		 options.inInputShareable=true;             
		 options.inTempStorage=new byte[100*1024];
		 //设置为true只读取图片信息，不会读取图片数据
		 options.inJustDecodeBounds=true;
		 //此时返回的bitmap为空
		 BitmapFactory.decodeFile(path, options);
		 //图片原始宽度
		 int w=options.outWidth;
		 //图片原始高度
		 int h=options.outHeight;
		 int widthRatio=w/width;
		 int heightRatio=h/height;
		 //压缩比例
		 int compressRatio=1;
		 
		 if (widthRatio>1 || heightRatio>1) {
			 //压缩比例取宽高比例较大者
			compressRatio=Math.max(widthRatio, heightRatio);
		}
		 
		 options.inSampleSize=compressRatio;
		 FileInputStream imgStream = null;
		 Bitmap mBitmap = null;
		 try {
			imgStream=new FileInputStream(pic);
			options.inJustDecodeBounds=false;
//			mDrawable=new BitmapDrawable(BitmapFactory.decodeStream(imgStream, null, options));
			//调用本地方法decodeFileDescriptor节省内存
			mBitmap=BitmapFactory.decodeFileDescriptor(imgStream.getFD(), null, options);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			try {
				if (imgStream!=null) {
					imgStream.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		 return mBitmap;
	 }
	
}
